package nju.bishe.weibo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nju.bishe.weibo.data.Address;
import nju.bishe.weibo.data.Position;
import nju.bishe.weibo.task.GenericTask;
import nju.bishe.weibo.task.TaskAdapter;
import nju.bishe.weibo.task.TaskListener;
import nju.bishe.weibo.task.TaskParams;
import nju.bishe.weibo.task.TaskResult;
import nju.bishe.weibo.ui.base.WithHeaderActivity;
import nju.bishe.weibo.util.WeiboLocationManager;
import weibo4android.WeiboException;
import weibo4android.org.json.JSONException;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class SignInActivity extends WithHeaderActivity {
	private static final String TAG = "SignSuggestActivity";
	private static Location currentLocation = null;
	private ListView sign_list;
	private static final String POSITION_ID = "positionId";
	private List<Position> positions;
	private Address currentAddress;
	private GenericTask mSignInTask;
	private LinearLayout ll_current;
	private TextView current_msg;
	private TextView current_short;
	private TextView current_addr;
	private SimpleAdapter  simpleAdapter;
	private Position currentPosition = null;
	private WeiboLocationManager weiboLocationManager = new WeiboLocationManager();
	  List<Map<String,String>> addr_map=new ArrayList<Map<String,String>>(); 
	  
	private TaskListener mSignInListener = new TaskAdapter() {
		
		
		
		@Override
		public void onPreExecute(GenericTask task) {
			current_short=(TextView)findViewById(R.id.signin_current_shortname);
			current_short.setText("获取位置信息中...");
		}

		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {

			try {
				currentAddress = TwitterApplication.mApi.geoToPosition(
						currentLocation.getLatitude(), currentLocation
								.getLongitude());
			} catch (WeiboException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			

			// 将Location转为Position
			if (currentLocation != null) {
				currentPosition = Position
						.constructFromLocation(currentLocation);
			}
			

			//显示当前位置
            current_msg=(TextView)findViewById(R.id.signin_current_msg);
        	current_short=(TextView)findViewById(R.id.signin_current_shortname);
        	current_addr=(TextView)findViewById(R.id.signin_current_full);
        	ll_current = (LinearLayout)findViewById(R.id.sign_current_layout);
        	
        	
            if(null==currentAddress){                	
            	current_msg.setText("糟糕~~由于被Google拒绝，没法详细定位当前位置，可尝试重新加载");
            	current_short.setVisibility(View.GONE);
            	current_addr.setVisibility(View.GONE);
            }
            else{
            	
            	current_short.setText(currentAddress.getWholeName());
                ll_current.setOnClickListener(new View.OnClickListener() {
                	  public void onClick(View v) {               
                		  Intent intent = new Intent(SignInActivity.this,SignPageActivity.class);
                          Bundle bundle = new Bundle();
                          bundle.putParcelable(POSITION_ID, currentPosition);
                          intent.putExtras(bundle);
                          startActivity(intent);
                	  }
                	  });
            }
            
			try {
				positions = weiboLocationManager
						.getNearByPostions(currentPosition);
			} catch (WeiboException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

              String[] from = {"name","desc"};
              int[] to = {R.id.sign_position_shortname,R.id.sign_position_full};
              //b2.show();
              for(int i =0; i<positions.size();i++){
              	Map<String,String> item=new HashMap<String,String>();
					item.put("name", positions.get(i).getName());
					item.put("desc", positions.get(i).getAddress());
					addr_map.add(item);
              }
              
			// 获得周围的positions
			WeiboLocationManager locationManager = new WeiboLocationManager();
			try {
				positions = locationManager.getNearByPostions(currentPosition);
			} catch (WeiboException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}

			sign_list = (ListView) findViewById(R.id.sign_suggest_list);
			
            simpleAdapter=new SimpleAdapter(SignInActivity.this,addr_map,R.layout.sign_location_item,from,to); 
			sign_list.setAdapter(simpleAdapter);


			// set lisenter
			sign_list.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long id) {
					Intent intent = new Intent(SignInActivity.this,
							SignPageActivity.class);
					Bundle bundle = new Bundle();
					bundle.putParcelable(POSITION_ID, positions.get(position));
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
			
			  
              
              searchButton.setOnClickListener(new View.OnClickListener() {
					
					public void onClick(View v) {
						
						try {
							positions = weiboLocationManager.getSearchedPostion(searchEdit.getText().toString(), currentLocation.getLatitude(), currentLocation
									.getLongitude());

							addr_map.clear();
				            for(int i =0; i<positions.size();i++){
				            	Map<String,String> item=new HashMap<String,String>();
								item.put("name", positions.get(i).getName());
								item.put("desc", positions.get(i).getAddress());
								addr_map.add(item);
				            }
				              
							if(addr_map.size()==0){
								ll_current.setVisibility(View.VISIBLE);
								current_msg.setText("无搜索结果");
		                    	current_short.setVisibility(View.GONE);
		                    	current_addr.setVisibility(View.GONE);
		                    	//sign_list.invalidate();  
								simpleAdapter.notifyDataSetChanged();
							}
							else{
								ll_current.setVisibility(View.GONE);
								simpleAdapter.notifyDataSetChanged();

		                    	//sign_list.invalidate();  
							}
						} catch (WeiboException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
		}

		@Override
		public String getName() {
			return "SignInTask";
		}
	};

	protected boolean _onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate()...");
		
		if(super._onCreate(savedInstanceState)){
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			requestWindowFeature(Window.FEATURE_PROGRESS);
		
			setContentView(R.layout.signin);
			initHeader(HEADER_STYLE_SEARCH);

			searchEdit.setHint("请输入搜索关键词");

		mSignInTask = new SignInTask();
		mSignInTask.setListener(mSignInListener);
		mSignInTask.execute();
		}
		return true;

	}

	private class SignInTask extends GenericTask {

		@Override
		protected TaskResult _doInBackground(TaskParams... params) {
			String serviceName = Context.LOCATION_SERVICE;
			LocationManager locationManager = (LocationManager) getSystemService(serviceName);
			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_FINE);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			criteria.setPowerRequirement(Criteria.POWER_LOW);
			String provider = locationManager.getBestProvider(criteria, true);
			long preTime = System.currentTimeMillis();
			long afterTime;
			while (currentLocation == null) {
				currentLocation = locationManager
						.getLastKnownLocation(provider);
				afterTime = System.currentTimeMillis();
				if ((afterTime - preTime) > 5000) // 超过5s
				{
					break;
				}
			}
			
			//get from huancun
			WeiboLocationManager weiboLocationManager = new WeiboLocationManager();
			Position position = weiboLocationManager.getPosition();
			currentLocation = new Location(provider);
			currentLocation.setLatitude(Double.parseDouble(position.getLatitude()));
			currentLocation.setLongitude(Double.parseDouble(position.getLongitude()));

			if (currentLocation != null) {
				return TaskResult.OK;
			} else {
				return TaskResult.FAILED;
			}
		}
	}

}